package com.raylu.day03basic;

import com.raylu.utils.IntSource;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Example3TypeErasing3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntSource())
                .map(r -> Tuple2.of(r, 1))
                .returns(Types.TUPLE(Types.INT, Types.INT))
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    // value1是输入元素
                    // value2是累加器
                    // 返回值是累加器
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return Tuple2.of(
                                value1.f0 + value2.f0,
                                value1.f1 + value2.f1
                        );
                    }
                })
                .map(r -> (double)(r.f0 / r.f1))
                .print();

        env
                .addSource(new IntSource())
                .map(r -> Tuple2.of(r, 1))
                .returns(Types.TUPLE(Types.INT, Types.INT))
                .keyBy(r -> 1)
                // 由于reduce的输入类型已经知道了，而又因为输入，累加器，输出的类型相同，所以无需进行类型注解
                .reduce((r1, r2) -> Tuple2.of(r1.f0 + r2.f0, r1.f1 + r2.f1))
                .map(r -> (double)(r.f0 / r.f1))
                .print();

        env.execute();
    }
}